from django.shortcuts import render
import json
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.conf import settings
import os


# Create your views here.
from .serializers import *
from rest_framework import viewsets
from .models import *


from rest_framework.pagination import PageNumberPagination
from rest_framework.decorators import action

# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend, CharFilter

from django_filters import FilterSet, DateFilter

from django.utils.timezone import make_aware
from datetime import datetime, timedelta


# views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.schemas import AutoSchema, coreapi
import coreschema

# from rest_framework.schemas.openapi import AutoSchema
from rest_framework import serializers
from coreapi import Field
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.db.models import F

# 当前时间
print(datetime.now())
print(type(datetime.now()))
now = make_aware(datetime.now())

# 时间范围：现在往前推7天，现在往后推3天
start_date = now - timedelta(days=7)
end_date = now + timedelta(days=3)

print(start_date)

print(end_date)


class MyPagination(PageNumberPagination):
    page_size = 100  # 设置默认分页长度为10
    page_size_query_param = "page_size"  # 允许通过查询参数改变分页长度
    max_page_size = 240  # 最大分页长度


# 能源数据过滤器
class EnergyFilter(FilterSet):
    datetime_field = DateFilter(label="日期时间", field_name="time", lookup_expr="gte")

    class Meta:
        model = Sj1
        fields = ["item", "val", "datetime_field"]


class EnergyView(APIView):
    # 设置默认的每页数据量
    page_size = 10
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="item",
                required=False,
                location="query",
                schema=coreschema.String(description="区域"),
            ),
            Field(
                name="val",
                required=False,
                location="query",
                schema=coreschema.String(description="能耗值"),
            ),
            Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
            Field(
                name="start_time",
                required=False,
                location="query",
                schema=coreschema.String(description="开始日期时间，格式示例：2024-07-01 16:34:42"),
            ),
            Field(
                name="end_time",
                required=False,
                location="query",
                schema=coreschema.String(description="结束日期时间，格式示例：2024-07-10 16:34:42"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = EnergySerializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        # queryset = OutputLoopa.objects.using("as_manage_analysis").annotate(staion_order=F('staion')).order_by('staion_order')
        queryset = Sj1.objects.using("energy_use_new").filter().order_by("time")
        # 获取请求的参数

        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        id = request.query_params.get("id")
        item = request.query_params.get("item")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if item is not None:
            queryset = queryset.filter(item__contains=item)
        if (start_time_param and end_time_param) is not None:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(time__gte=start_time_param_trans, time__lte=end_time_param_trans)
        else:
            print("aaaaa")

        return queryset
